#!/bin/bash

# x11vnc UTF-8剪贴板测试脚本
# 用于验证UTF-8剪贴板调试功能是否正常工作

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 项目路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
X11VNC_BIN="$SCRIPT_DIR/result/bin/x11vnc"

print_info "=== x11vnc UTF-8剪贴板测试 ==="
print_info "二进制文件: $X11VNC_BIN"

# 检查二进制文件
if [ ! -f "$X11VNC_BIN" ]; then
    print_error "找不到x11vnc二进制文件: $X11VNC_BIN"
    exit 1
fi

# 检查权限
if [ ! -x "$X11VNC_BIN" ]; then
    print_info "设置执行权限..."
    chmod +x "$X11VNC_BIN"
fi

# 显示版本信息
print_info "版本信息:"
"$X11VNC_BIN" -version 2>/dev/null || echo "无法获取版本信息"

# 检查UTF-8剪贴板功能
print_info "检查UTF-8剪贴板功能集成..."
if strings "$X11VNC_BIN" | grep -q "clipboard_utf8.c"; then
    print_success "✅ UTF-8剪贴板模块已集成"
else
    print_error "❌ UTF-8剪贴板模块未找到"
    exit 1
fi

if strings "$X11VNC_BIN" | grep -q "xcut_receive_utf8"; then
    print_success "✅ UTF-8剪贴板接收函数已集成"
else
    print_error "❌ UTF-8剪贴板接收函数未找到"
    exit 1
fi

if strings "$X11VNC_BIN" | grep -q "CLIPBOARD_DEBUG"; then
    print_success "✅ 剪贴板调试功能已集成"
else
    print_error "❌ 剪贴板调试功能未找到"
    exit 1
fi

# 检查调试开关状态
print_info "检查调试开关状态..."
if strings "$X11VNC_BIN" | grep -q "clipboard_debug_enabled"; then
    print_success "✅ 调试开关变量已集成"
else
    print_error "❌ 调试开关变量未找到"
    exit 1
fi

# 显示UTF-8相关字符串
print_info "UTF-8剪贴板相关功能:"
strings "$X11VNC_BIN" | grep -E "(UTF8|utf8)" | head -10

# 显示调试相关字符串
print_info "剪贴板调试相关功能:"
strings "$X11VNC_BIN" | grep -E "(CLIPBOARD_DEBUG|clipboard_debug)" | head -5

# 测试建议
print_info "=== 测试建议 ==="
print_info "1. 启动x11vnc服务器:"
echo "   $X11VNC_BIN -display :0 -rfbport 5900 -forever -o /tmp/x11vnc_utf8_test.log"
print_info ""
print_info "2. 在另一个终端监控日志:"
echo "   tail -f /tmp/x11vnc_utf8_test.log | grep CLIPBOARD_DEBUG"
print_info ""
print_info "3. 测试UTF-8字符复制:"
echo "   - 复制中文字符: 你好世界"
echo "   - 复制特殊字符: café naïve résumé"
echo "   - 复制表情符号: 😊🎉"
print_info ""
print_info "4. 观察调试输出中的UTF-8处理过程"
print_info ""
print_info "5. 检查URL编码/解码功能:"
echo "   - 查看日志中的URL编码字符串"
echo "   - 验证中文字符是否正确传输"

# 创建测试日志目录
mkdir -p /tmp/x11vnc_test

print_success "=== 验证完成 ==="
print_info "✅ x11vnc UTF-8剪贴板功能已成功集成"
print_info "✅ 调试日志默认开启"
print_info "✅ 可以开始手动测试"

print_info "测试日志目录: /tmp/x11vnc_test"
print_info "如需清理测试环境，删除该目录即可"
